package com.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.demo.dto.CommentFormDTO;
import com.demo.dto.Result;
import com.demo.entity.Comment;
import com.demo.mapper.CommentMapper;
import com.demo.query.CommentListQuery;
import com.demo.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.utils.UserHolder;
import com.demo.vo.CommentVO;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zeng
 * @since 2022-03-23
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Override
    public Result<Comment> postComment(CommentFormDTO commentFormDTO) {
        Comment comment = BeanUtil.copyProperties(commentFormDTO, Comment.class);
        comment.setUserId(UserHolder.getUser().getUserId());
        try {
            save(comment);
            return Result.ok(getById(comment.getCommentId()), "评论新增成功");
        }
        catch (Exception e) {
            return Result.fail("数据库插入有误（检查外键）");
        }
    }

    @Override
    public Result<Comment> delete(Integer commentId) {
        Integer userId = UserHolder.getUser().getUserId();
        // 先查询这个用户是否有发表过这个评论
        Comment comment = query().eq("comment_id", commentId).eq("user_id", userId).one();
        if (comment == null) {
            // 当前用户没有发表这个评论
            return Result.fail("用户没有发表这个评论，无法删除");
        }
        // 有发表，进行删除
        removeById(commentId);
        return Result.ok(comment, "这条评论删除成功");
    }

    @Override
    public Result<List<CommentVO>> getListByAnswerId(CommentListQuery commentListQuery) {
        List<CommentVO> commentVOList = baseMapper.getListByAnswerId(commentListQuery);
        if (commentVOList.isEmpty()) {
            return Result.fail("评论区暂无评论");
        }
        return Result.ok(commentVOList, commentVOList.size());
    }

}
